// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import {toolList} from "./handControl";
import {keyType, keyUsing} from "./keyMediator";
import {colorList} from "./bgColorControl";
import gameData from "./gameData";
import settingMediator from "../framework/settingMediator";
import AudioManage, {soundList} from "../framework/AudioManage";
import Tool from "../framework/Tool";
import sceneMediator from "../framework/sceneMediator";

const {ccclass, property} = cc._decorator;

//宝箱用途钥匙图片
let boxKeyPic =  ["dj-x03c","dj-x04c","dj-x01c","dj-x02c","dj-x05c","dj-x07c"];
let diamondPic = ["dj-20"];
let advenPic = ["icon001","icon002","icon003","icon004","icon005","icon006","icon007"];
let canPic = ["dj-21","cd004"];

@ccclass
export default class roleMediator extends cc.Component {

    @property({displayName : "开始穿过"})
    isOpenCross : boolean = false;

    @property({displayName : "跳场景获得道具"})
    getTool : boolean = false;

    @property({displayName : "开启人物运动监听"})
    moveListing : boolean = false;

    @property({displayName : "开启苹果监听"})
    pumpkinListen : boolean = false;

    @property({displayName : "开启相机跟随监听"})
    cameraFollow : boolean = false;

    @property({displayName : "开启无尽模式死亡安全复活"})
    dieSafeLive : boolean = false;

    @property({displayName : "开始相机移动最大距离"})
    cameraMoveDistance = 0;

    @property({displayName : "相机移动最大范围"})
    cameraMoveRange = cc.v2(0,0);

    @property({displayName : "初始朝向"})
    faceDir =  1;

    @property({displayName : "死亡变幽灵"})
    dieBecomeGhost = false;

    @property({displayName : "默认使用皮肤"})
    defaultSkin  = -1;

    @property({displayName : "变身指定皮肤"})
    assignSkin  = -1;

    @property({displayName : "初始化皮肤"})
    initSkin  =  true;

    @property({type : cc.Component.EventHandler,displayName : "触发事件"})
    toolEvent : cc.Component.EventHandler[] = [];

    processWater : boolean = false;

    curProcessKey = null;

    watchControl = false;

    curToolType = 0;

    lastPos = null;

    initPos = null;

    isGameOver : boolean = false;

    isBecomeGhost = false;

    showDefaultSkin = true;

    static LastRolePosition = null;

    protected onLoad(): void {

        if(this.node.getChildByName("tool").children[0]){
            this.node.getChildByName("tool").children[0].on("touchend",this.BecomeGhost,this);
        }

        this.initPosition = this.node.x;
        this.initLocation = cc.v2(this.node.x,this.node.y);

        if(roleMediator.LastRolePosition != null && !this.dieSafeLive){
            this.node.x = roleMediator.LastRolePosition.x;
            this.node.y = roleMediator.LastRolePosition.y;
            roleMediator.LastRolePosition = null;
        }

        this.lastPos = this.node.position;
        this.initPos = this.node.position;

        this.node.getChildByName("spine").scaleX = 0.3 * this.faceDir;
        this.node.getChildByName("spine").scaleY = 0.3;
        let spk = this.node.getChildByName("spine").getComponent(sp.Skeleton);
        spk.setSkin("pf02");
        spk.setAnimation(0,"animation",true);

        if(this.getTool){
            if(gameData.keyUsingIndex == -1) return;
            this.curProcessKey = gameData.keyUsingIndex;
            this.setRoleProcessKey(boxKeyPic[gameData.keyUsingIndex - 1]);
            gameData.keyUsingIndex = -1;
        }

        cc.game.on("gameOver",()=>{
            this.isGameOver = true;
        });

        cc.game.on("setGameRoleSkin",(index,special?)=>{
            this.node.getChildByName("spine").scaleX = 0.3 * this.node.getChildByName("spine").scaleX / Math.abs(this.node.getChildByName("spine").scaleX);
            this.node.getChildByName("spine").scaleY = 0.3 * this.node.getChildByName("spine").scaleY / Math.abs(this.node.getChildByName("spine").scaleY);
        });
    }

    protected onDestroy(): void {
        cc.game.off("gameOver");
        cc.game.off("setGameRoleSkin");
        cc.game.off("becomeGhost")
    }

    loadTitleSkin(node,url){
        cc.loader.loadRes(url,sp.SkeletonData,(err,res)=>{
            if(err){
                console.log(err);
                return;
            }
            node.skeletonData = res;
        })
    }

    loadTitlePic(url,node){
        console.log(url);
        cc.loader.loadRes("img/adventurer/" + url,cc.SpriteFrame,(err,res)=>{
            if(err){
                console.log(err);
                return;
            }
            node.getComponent(cc.Sprite).spriteFrame = res;
        })
    }

    BecomeGhost(){
        cc.game.emit("becomeGhost",true);
    }

    keyNode = null;
    onBeginContact(contact, self, other) {
        if(this.isGameOver) return;
        if(!this.isBecomeGhost){
            if(other.node.group == "default" || other.node.group == "stab"){

                if(this.lastPos != null && this.node.position.y - this.lastPos.y <= -250){
                    console.log("高处掉落");
                    settingMediator.doVibration(1);
                }
                this.lastPos = this.node.position;
            }

            if(other.node.group == "tool"){
                cc.game.emit("setCurCheckNode",other);
                let type = other.node.getComponent("toolTypeList").toolType;
                if(type == toolList.openSwitch || type == toolList.sceneReversal){
                    other.node.getChildByName("bg").active = true;
                    cc.game.emit("setHandStatus",true,type,other);
                }else if(type == toolList.showEggWindow){
                    if(!gameData.showConversation){
                        cc.game.emit("shieldPressKey", true);
                        gameData.showConversation = true;
                        gameData.savePrinceLevelLocalPart1();
                        cc.game.emit("showEggView",1);
                    }else{
                        cc.game.emit("setHandStatus",true,type,other);
                    }
                }else{
                    cc.game.emit("setHandStatus",true,type,other);
                }

            }

            if(other.node.group == "key"){
                AudioManage.playSFX(soundList.pickTool,false);
                if(this.curProcessKey != keyType.emptyKey){
                    this.curProcessKey = other.node.getComponent("keyMediator").curKey;
                    if(this.watchControl){
                        this.setRoleProcessKey(canPic[1]);
                    }else{
                        this.setRoleProcessKey(boxKeyPic[this.curProcessKey - 1]);
                    }
                    if(other.node.getComponent("keyMediator").keyPurpose == keyUsing.usingMoreScene){
                        gameData.keyUsingIndex = this.curProcessKey;
                    }
                }
                if(other.node.parent.name == "light" || other.node.parent.name == "light copy"){
                    other.node.parent.destroy();
                }else{
                    if(sceneMediator.getShowScene() == 11){
                        other.node.active = false;
                        this.keyNode = other.node;
                    }else{
                        other.node.destroy();
                    }
                }
            }

            if(other.node.group == "diamond"){
                AudioManage.playSFX(soundList.pickTool,false);
                this.setRoleProcessKey(diamondPic[0]);
                other.node.destroy();
                cc.Component.EventHandler.emitEvents(this.toolEvent,[]);
            }

            if(other.node.group == "jerrican"){
                if(other.node.getComponent("jerricanMediator").touchRole){
                    AudioManage.playSFX(soundList.pickTool,false);
                    this.curProcessKey = 11;
                    this.setRoleProcessKey(canPic[0]);
                    other.node.destroy();
                    cc.Component.EventHandler.emitEvents(this.toolEvent,[]);
                }
            }

            if(other.node.group == "controler"){
                AudioManage.playSFX(soundList.pickTool,false);
                // this.curProcessKey = 12;
                this.watchControl = true;
                this.setRoleProcessKey(canPic[1]);
                other.node.destroy();
                cc.Component.EventHandler.emitEvents(this.toolEvent,[]);
            }

            if(other.node.group == "tv"){
                // AudioManage.playSFX(soundList.pickTool,false);
                if(this.watchControl){
                    this.watchControl = false;
                    this.setRoleProcessKey(null);
                    other.node.destroy();
                    this.keyNode.active = true;
                    cc.Component.EventHandler.emitEvents(this.toolEvent,[2]);
                }
            }

            if(other.node.group == "door"){
                other.node.getComponent("doorMediator").doorOpenJudge(this.curProcessKey,()=>{
                    this.curProcessKey = null;
                    this.setRoleProcessKey(null);
                });
            }

            if(other.node.group == "stab"){
                if(this.dieBecomeGhost){
                    this.node.getComponent(cc.RigidBody).linearVelocity = cc.v2(0,0);
                    cc.game.emit("shieldPressKey", true);
                    cc.game.emit("becomeGhost",true);
                }else{
                    if(this.dieSafeLive){
                        cc.game.emit("shieldPressKey", true);
                        let spk = this.node.getChildByName("spine").getComponent(sp.Skeleton);
                        spk.setAnimation(0,"die",false);
                        cc.Component.EventHandler.emitEvents(this.toolEvent,[]);
                    }else{
                        this.isGameOver = true;
                        cc.game.emit("setColor",colorList.green);
                        cc.game.emit("shieldPressKey",true);
                        cc.game.emit("GameOver");
                        settingMediator.doVibration(2);
                        let spk = this.node.getChildByName("spine").getComponent(sp.Skeleton);
                        spk.setAnimation(0,"die",false);
                        cc.game.emit("petDie");
                        this.scheduleOnce(()=>{
                            cc.game.emit("gameLose",1);
                        },2);
                    }
                }
            }


            if(other.node.group == "monster"){
                if(this.processWater || (sceneMediator.getShowScene() == 28 && gameData.getCurUseRoleSkin() == 14)){

                }else{
                    this.isGameOver = true;
                    cc.game.emit("setColor",colorList.green);
                    cc.game.emit("shieldPressKey",true);
                    cc.game.emit("GameOver");
                    settingMediator.doVibration(2);
                    let spk = this.node.getChildByName("spine").getComponent(sp.Skeleton);
                    spk.setAnimation(0,"die",false);
                    cc.game.emit("petDie");
                    this.scheduleOnce(()=>{
                        cc.game.emit("gameLose",1);
                    },2);
                }
            }

            if(other.node.group == "pumpkin"){
                cc.game.emit("addPumpkin");
                AudioManage.playSFX(soundList.pickTool);
                if(other.node.getComponent("pumpkinMediator")){
                    other.node.getComponent("pumpkinMediator").setPumpkinShowState();
                }
                other.node.destroy();
                if(this.pumpkinListen){
                    cc.Component.EventHandler.emitEvents(this.toolEvent,[]);
                }
            }

            if(other.node.group == "water"){
                this.processWater = true;
                this.node.getChildByName("spine").active = false;
                other.node.destroy();
            }

            if(other.node.group == "maPiece"){
                AudioManage.playSFX(soundList.pickTool);
                let order = other.node.getComponent("pieceMediator").pieceIndex;
                if(order == 2){
                    gameData.colorfulPiece[1][1] = 1;
                    other.node.children[0].active = true;
                    other.node.children[1].active = false;
                }else if(order == 3){
                    gameData.colorfulPiece[1][2] = 1;
                    other.node.active = false;
                }
                gameData.saveColorfulPiece();
                cc.tween(other.node).to(0.5,{
                    position : cc.v2(0,0)
                }).call(()=>{
                    other.node.destroy();
                    Tool.loadPrefab("prefabs/getPiece",res=>{
                        let view = cc.instantiate(res);
                        view.getComponent("getMaPiece").setCallBack(order);
                        view.parent = cc.find("Canvas");
                    })
                }).start();
            }

            if(other.node.group == "piece"){
                if(sceneMediator.getShowScene() == 1 && other.node.getComponent("pieceMediator").maskNode){
                    other.node.getComponent("pieceMediator").maskNode.active = false;
                }
                AudioManage.playSFX(soundList.pickTool);
                let order = other.node.getComponent("pieceMediator").pieceIndex;
                if(order == 4){
                    gameData.colorfulPiece[0][3] = 1;
                }else if(order == 5){
                    gameData.colorfulPiece[0][4] = 1;
                }else if(order == 6){
                    gameData.colorfulPiece[0][5] = 1;
                }
                gameData.saveColorfulPiece();

                cc.tween(other.node).to(0.5,{
                    position : cc.v2(0,0)
                }).call(()=>{
                    other.node.destroy();
                    Tool.loadPrefab("prefabs/getSkin",res=>{
                        let view = cc.instantiate(res);
                        if(gameData.getColorfulPieceNumber(gameData.colorfulPiece[0]) == 7){
                            view.getComponent("getSkinMediator").setCallBack(true,order);
                        }else{
                            view.getComponent("getSkinMediator").setCallBack(false,order);
                        }
                        view.parent = cc.find("Canvas");
                    })
                }).start();
            }

            if(other.node.group == "one"){
                AudioManage.playSFX(soundList.pickTool);
                let order = other.node.getComponent("pieceMediator").pieceIndex;
                let seeVideo = false;
                if(order == 2){
                    // gameData.colorfulPiece[0][1] = 1;
                    seeVideo = true;
                } else if(order == 4){
                    // gameData.colorfulPiece[0][3] = 1;
                    seeVideo = true;
                }else if(order == 6){
                    // gameData.colorfulPiece[0][5] = 1;
                    seeVideo = true;
                }
                other.node.zIndex = 500;
                let pos = cc.v2(other.node.x,other.node.y);
                cc.tween(other.node).to(0.3,{
                    position : cc.v2(cc.Camera.main.node.x,cc.Camera.main.node.y)
                }).call(()=>{
                    other.node.active = false;
                    Tool.loadPrefab("prefabs/callDragonBall",(res)=>{
                        let view = cc.instantiate(res);
                        view.getComponent("callDragonBall").setCallBack(order,seeVideo,()=>{
                            other.node.destroy();
                        },()=>{
                            other.node.x = pos.x;
                            other.node.y = pos.y;
                            other.node.active = true;
                        });
                        view.parent = cc.find("Canvas");
                    })
                }).start();
            }
        }else{
            if(other.node.group == "lightning"){
                this.isGameOver = true;
                cc.game.emit("setColor",colorList.green);
                cc.game.emit("shieldPressKey",true);
                cc.game.emit("GameOver");
                settingMediator.doVibration(2);
                let spk = this.node.getChildByName("spine").getComponent(sp.Skeleton);
                spk.setAnimation(0,"resurrected",false);
                cc.game.emit("petDie");
                this.scheduleOnce(()=>{
                    cc.game.emit("gameLose",1);
                },2);
            }
        }

    }

    onEndContact(contact, self, other) {
        if(other.node.group == "tool"){
            let type = other.node.getComponent("toolTypeList").toolType;
            if(type == toolList.openSwitch || type == toolList.sceneReversal){
                other.node.getChildByName("bg").active = false;
            }
            // cc.game.emit("setHandStatus",false,toolList.openSwitch,other);
            cc.game.emit("setHandStatus",false,type,other);
        }
    }


    setRoleProcessKey(url){
        if(url != null){
            cc.loader.loadRes("img/level/" + url,cc.SpriteFrame,(error, resource) => {
                if(error){
                    console.log(error);
                    return;
                }
                this.node.getChildByName("tool").getComponent(cc.Sprite).spriteFrame = resource;
            })
        }else{
            this.node.getChildByName("tool").getComponent(cc.Sprite).spriteFrame = null;
        }
    }


    initState = 0;
    openCheck = false;
    titleIndex = 0;
    initPosition = 0;
    initLocation = cc.v2(0,0);
    isCameraMoving = false;

    protected update(dt: number): void {
        if(this.isCameraMoving) return;
        if(this.cameraMoveDistance != 0){
            if(this.node.x > 0 ){
                if(cc.Camera.main.node.x + (this.node.x - this.initPosition) >= this.cameraMoveDistance){
                    cc.Camera.main.node.x = this.cameraMoveDistance;
                }else if(cc.Camera.main.node.x + (this.node.x - this.initPosition) <= 0){
                    cc.Camera.main.node.x = 0;
                }else{
                    if(this.node.x <= this.cameraMoveDistance){
                        cc.Camera.main.node.x += this.node.x - this.initPosition;
                    }
                }
            }
            this.initPosition = this.node.x;
        }

        if(this.cameraMoveRange.x != 0 || this.cameraMoveRange.y != 0){
            if(this.node.x > 0 ){
                if(cc.Camera.main.node.x + (this.node.x - this.initLocation.x) >= this.cameraMoveRange.x){
                    cc.Camera.main.node.x = this.cameraMoveRange.x;
                }else if(cc.Camera.main.node.x + (this.node.x - this.initLocation.x) <= 0){
                    cc.Camera.main.node.x = 0;
                }else{
                    if(this.node.x <= this.cameraMoveRange.x){
                        cc.Camera.main.node.x += this.node.x - this.initLocation.x;
                    }
                }
            }

            if(this.node.y > 0 ){
                if(cc.Camera.main.node.y + (this.node.y - this.initLocation.y) >= this.cameraMoveRange.y){
                    cc.Camera.main.node.y = this.cameraMoveRange.y;
                }else if(cc.Camera.main.node.y + (this.node.y - this.initLocation.y) <= 0){
                    cc.Camera.main.node.y = 0;
                }else{
                    if(this.node.y <= this.cameraMoveRange.y){
                        if(this.node.y > 750 + 750 / 2){
                            cc.Camera.main.node.y = this.cameraMoveRange.y;
                        }else{
                            if(this.node.y >= 750 && this.node.y <= 750 + 750 / 2){
                                cc.Camera.main.node.y = 750;
                            }else{
                                cc.Camera.main.node.y += this.node.y - this.initLocation.y;
                            }
                        }
                    }
                }
            }
            this.initLocation = cc.v2(this.node.x,this.node.y);
        }

        if(this.cameraFollow){
            // let pos = cc.Camera.main.node.convertToWorldSpaceAR(cc.v2(0,0));
            // let pos2= cc.find("Canvas").convertToNodeSpaceAR(pos);
           if(this.node.x >= 1625 / 2 && this.titleIndex == 0){
               this.titleIndex ++;
               cc.Camera.main.node.x += 1625;
               cc.game.emit("setTitle",[this.titleIndex]);
           }else if(this.node.x < 1625 / 2 && this.titleIndex == 1){
               this.titleIndex--;
               cc.Camera.main.node.x -= 1625;
               cc.game.emit("setTitle",[this.titleIndex]);
           }else if(this.node.x >= 1625 * 3 / 2 && this.titleIndex == 1){
                this.titleIndex ++;
                cc.Camera.main.node.x += 1625;
                cc.game.emit("setTitle",[this.titleIndex]);
            }else if(this.node.x < 1625 * 3 / 2 && this.titleIndex == 2){
                this.titleIndex--;
                cc.Camera.main.node.x -= 1625;
                cc.game.emit("setTitle",[this.titleIndex]);
            }else if(this.node.x >= 1625 * 5 / 2 && this.titleIndex == 2){
               this.titleIndex ++;
               cc.Camera.main.node.x += 1625;
               cc.game.emit("setTitle",[this.titleIndex]);
           }else if(this.node.x < 1625 * 5 / 2 && this.titleIndex == 3){
               this.titleIndex--;
               cc.Camera.main.node.x -= 1625;
               cc.game.emit("setTitle",[this.titleIndex]);
           }
        }

        if(this.isOpenCross){
            if(this.node.x < -(cc.winSize.width / 2 - this.node.width / 2)){
                this.node.x = cc.winSize.width / 2;
                this.node.y += 30;
                // for(let i in gameData.getPetCurSkin()){
                //     let pos = null;
                //     if(parseInt(i) == 1){
                //         pos = this.node.getChildByName("petNode1").convertToWorldSpaceAR(cc.v2(0,0));
                //     }else if(parseInt(i) == 2){
                //         pos = this.node.getChildByName("petNode2").convertToWorldSpaceAR(cc.v2(0,0));
                //     }else{
                //         if(this.node.getChildByName("petNode3")){
                //             pos = this.node.getChildByName("petNode3").convertToWorldSpaceAR(cc.v2(0,0));
                //         }
                //     }
                //     if(pos != null){
                //         let pos2 = cc.find("Canvas").convertToNodeSpaceAR(pos);
                //         if(cc.find("Canvas/petGroup").children[i]){
                //             cc.find("Canvas/petGroup").children[i].x = pos2.x;
                //             cc.find("Canvas/petGroup").children[i].y = pos2.y;
                //         }
                //     }
                // }
            }else if(this.node.x > (cc.winSize.width / 2 - this.node.width / 2)){
                this.node.x = -cc.winSize.width / 2;
                this.node.y += 30;
                // for(let i in gameData.getPetCurSkin()){
                //     let pos = null;
                //     if(parseInt(i) == 1){
                //         pos = this.node.getChildByName("petNode1").convertToWorldSpaceAR(cc.v2(0,0));
                //     }else if(parseInt(i) == 2){
                //         pos = this.node.getChildByName("petNode2").convertToWorldSpaceAR(cc.v2(0,0));
                //     }else{
                //         if(this.node.getChildByName("petNode3")){
                //             pos = this.node.getChildByName("petNode3").convertToWorldSpaceAR(cc.v2(0,0));
                //         }
                //     }
                //     if(pos != null){
                //         let pos2 = cc.find("Canvas").convertToNodeSpaceAR(pos);
                //         if(cc.find("Canvas/petGroup").children[i]){
                //             cc.find("Canvas/petGroup").children[i].x = pos2.x;
                //             cc.find("Canvas/petGroup").children[i].y = pos2.y;
                //         }
                //     }
                // }
            }
        }

        if(this.moveListing && !this.openCheck && !this.isGameOver){
            if(this.node.x > this.initPos.x){
                let curState = this.node.getComponent(cc.RigidBody).linearVelocity.x;
                if(this.initState > 0 && curState <= 10){
                    this.openCheck = true;
                    cc.game.emit("shieldPressKey",true);
                    cc.Component.EventHandler.emitEvents(this.toolEvent,[]);
                    console.log("游戏结束");
                }
                this.initState = this.node.getComponent(cc.RigidBody).linearVelocity.x;
            }
        }
    }
}
